package com.xinke.juc.case03;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author：xinke
 * @Date：2025/9/30
 * @Desc: 两阶段终止模式 - 利用停止标记
 */
@Slf4j
public class TestInterrupt04 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTerminationStopFlag tptInterrupt = new TwoPhaseTerminationStopFlag();
        tptInterrupt.start();

        Thread.sleep(3500);
        log.info("stop");
        tptInterrupt.stop();
    }
}

// 停止标记用 volatile 是为了保证该变量在多个线程之间的可见性
// 我们的例子中，即主线程把它修改为 true 对 t1 线程可见
@Slf4j
class TwoPhaseTerminationStopFlag {
    private Thread thread;
    private volatile boolean stop = false;

    public void start() {
        thread = new Thread(() -> {
            while (true) {
                Thread current = Thread.currentThread();
                if (stop) {
                    log.info("料理后事。。。");
                    break;
                }
                try {
                    Thread.sleep(1000);
                    log.info("将结果保存");
                } catch (InterruptedException e) {
                    current.interrupt();
                }
                //执行监控操作
            }
        }, "监控线程");
        thread.start();
    }

    public void stop() {
        stop = true;
    }
}